package handler

import (
	"boy-go/middlewares"
	"boy-go/modules/system/service"
	"boy-go/modules/system/vo"
	"boy-go/pkg/request"
	"boy-go/pkg/response"
	"boy-go/pkg/xnum"
	"github.com/gin-gonic/gin"
	"strings"
)

// AddSysRoleRouter 添加路由
func AddSysRoleRouter(group *gin.RouterGroup) {
	group.GET("/role/:id", middlewares.HasPermission("system:role:query"), get_role)
	group.GET("/role/list", middlewares.HasPermission("system:role:list"), list_role)
	group.GET("/role/optionselect", middlewares.HasPermission("system:role:query"), options_role)
	group.GET("/role/deptTree/:id", middlewares.HasPermission("system:role:query"), deptTree_role) // 根据用户编号获取授权角色
	group.GET("/role/authUser/allocatedList", middlewares.HasPermission("system:role:list"), allocatedList_role)
	group.GET("/role/authUser/unallocatedList", middlewares.HasPermission("system:role:list"), unallocatedList_role)
	group.POST("/role", middlewares.HasPermission("system:role:add"), middlewares.Logger("角色管理", middlewares.INSERT), add_role)
	group.PUT("/role", middlewares.HasPermission("system:role:edit"), middlewares.Logger("角色管理", middlewares.UPDATE), edit_role)
	group.DELETE("/role/:ids", middlewares.HasPermission("system:role:remove"), middlewares.Logger("角色管理", middlewares.DELETE), del_role)
	group.PUT("/role/dataScope", middlewares.HasPermission("system:role:edit"), middlewares.Logger("角色管理", middlewares.UPDATE), dataScope_role)
	group.PUT("/role/authUser/cancel", middlewares.HasPermission("system:role:edit"), middlewares.Logger("角色管理", middlewares.GRANT), authUser_cancel_role)
	group.PUT("/role/authUser/cancelAll", middlewares.HasPermission("system:role:edit"), middlewares.Logger("角色管理", middlewares.GRANT), authUser_cancelAll_role)
	group.PUT("/role/authUser/selectAll", middlewares.HasPermission("system:role:edit"), middlewares.Logger("角色管理", middlewares.GRANT), authUser_selectAll_role)
}

// get_role
// @Summary 获取角色表详情
// @Description 获取角色表详情（管理页面）
// @Tags system-role
// @Accept json
// @Produce json
// @Param id path string true "ID"
// @Success 200 {object} response.R[vo.SysRoleModel] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/role/{id} [get]
func get_role(ctx *gin.Context) {
	var idStr = ctx.Param("id")
	id := xnum.Str2int64(idStr)
	m, err := service.NewSysRoleService().GetById(id)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, m)
}

// list_role
// @Summary 获取角色表列表
// @Description 获取角色表列表（管理页面）
// @Tags system-role
// @Accept json
// @Produce json
// @Success 200 {object} response.R[PageRes[vo.SysRoleModel]] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/role/list [get]
func list_role(ctx *gin.Context) {
	req := vo.QuerySysRoleReq{}
	if err := ctx.BindQuery(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	req.Params = request.BindFormParams(ctx)
	page, err := service.NewSysRoleService().List(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxDataTable(ctx, page.List, page.Total)
}

// add_role
// @Summary 新增角色表
// @Description 新增角色表（管理页面）
// @Tags system-role
// @Accept json
// @Produce json
// @Param req body  vo.AddSysRoleReq true "req"
// @Success 200 {object} response.R[vo.AddSysRoleRsp] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/role [post]
func add_role(ctx *gin.Context) {
	var req vo.AddSysRoleReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	roleService := service.NewSysRoleService()
	if roleService.CheckRoleNameUnique(-1, req.RoleKey) {
		response.AjaxFail(ctx, response.ServerError, "新增角色'"+*req.RoleName+"'失败，角色名称已存在")
		return
	} else if roleService.CheckRoleKeyUnique(-1, req.RoleKey) {
		response.AjaxFail(ctx, response.ServerError, "新增角色'"+*req.RoleName+"'失败，角色权限已存在")
		return
	}
	m, err := roleService.Add(&req)
	if err != nil {
		response.AjaxFailCode(ctx, response.ServerError)
	} else {
		response.AjaxSuccess(ctx, m)
	}
}

// edit_role
// @Summary 编辑角色表
// @Description 编辑角色表（管理页面）
// @Tags system-role
// @Accept json
// @Produce json
// @Param req body  vo.EditSysRoleReq true "req"
// @Success 200 {object} response.R[vo.EditSysRoleRsp] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/role [put]
func edit_role(ctx *gin.Context) {
	var req vo.EditSysRoleReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	roleService := service.NewSysRoleService()
	err := roleService.CheckRoleAllowed(&req.RoleId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err = roleService.CheckRoleDataScope(req.RoleId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	if roleService.CheckRoleNameUnique(-1, req.RoleKey) {
		response.AjaxFail(ctx, response.ServerError, "新增角色'"+*req.RoleName+"'失败，角色名称已存在")
		return
	} else if roleService.CheckRoleKeyUnique(-1, req.RoleKey) {
		response.AjaxFail(ctx, response.ServerError, "新增角色'"+*req.RoleName+"'失败，角色权限已存在")
		return
	}
	m, err := service.NewSysRoleService().Edit(&req)
	if err != nil {
		response.AjaxError(ctx, err)
	} else {
		response.AjaxSuccess(ctx, m)
	}
}

// del_role
// @Summary 删除角色表
// @Description 删除角色表（管理页面）
// @Tags system-role
// @Accept json
// @Produce json
// @Success 200 {object} response.R[string] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/role [delete]
func del_role(ctx *gin.Context) {
	var idsStr = ctx.Param("ids")
	ids := strings.Split(idsStr, ",")
	roleIds := make([]*int64, 0)
	for _, id := range ids {
		roleId := xnum.Str2int64(id)
		roleIds = append(roleIds, &roleId)
	}
	err := service.NewSysRoleService().DeleteRoleByIds(roleIds)
	if err != nil {
		response.AjaxError(ctx, err)
	} else {
		response.AjaxSuccess(ctx, nil)
	}
}

func dataScope_role(ctx *gin.Context) {
	var req vo.EditSysRoleReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	roleService := service.NewSysRoleService()
	err := roleService.CheckRoleAllowed(&req.RoleId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err = roleService.CheckRoleDataScope(req.RoleId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err = roleService.AuthDataScope(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, nil)
}

func options_role(ctx *gin.Context) {
	roles := service.NewSysRoleService().SelectRoleAll()
	response.AjaxSuccess(ctx, roles)
}
func deptTree_role(ctx *gin.Context) {
	var idStr = ctx.Param("id")
	roleId := xnum.Str2int64(idStr)
	depeService := service.NewSysDeptService()
	checkedKeys := depeService.SelectDeptListByRoleId(roleId)
	ajax := response.NewAjaxResultSuccess()
	ajax.Put("checkedKeys", checkedKeys)
	ajax.Put("depts", depeService.SelectDeptTreeList(&vo.QuerySysDeptReq{}))
	response.AjaxResponse(ctx, ajax)
}
func allocatedList_role(ctx *gin.Context) {
	req := vo.QuerySysUserReq{}
	err := ctx.BindQuery(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	req.Params = request.BindFormParams(ctx)
	rsp, err := service.NewSysUserService().SelectAllocatedList(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxDataTable(ctx, rsp.List, rsp.Total)
}
func unallocatedList_role(ctx *gin.Context) {
	req := vo.QuerySysUserReq{}
	err := ctx.BindQuery(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	req.Params = request.BindFormParams(ctx)
	rsp, err := service.NewSysUserService().SelectUnallocatedList(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxDataTable(ctx, rsp.List, rsp.Total)
}

// 取消授权用户
func authUser_cancel_role(ctx *gin.Context) {
	req := vo.UserRoleReq{}
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err := service.NewSysRoleService().DeleteAuthUser(req.RoleId, req.UserId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, nil)
}

// 批量取消授权用户
func authUser_cancelAll_role(ctx *gin.Context) {
	req := vo.BatchRoleUserReq{}
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err := service.NewSysRoleService().DeleteAuthUsers(req.RoleId, req.UserIds)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, nil)
}

func authUser_selectAll_role(ctx *gin.Context) {
	req := vo.BatchRoleUserReq{}
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err := service.NewSysRoleService().CheckRoleDataScope(req.RoleId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err = service.NewSysRoleService().InsertAuthUsers(req.RoleId, req.UserIds)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, nil)
}
